package com.haidechizi.i18n.common.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

@Slf4j
public class MappingBindingInitializing implements ApplicationListener<ContextRefreshedEvent> {

    private volatile boolean init = false;

    /**
     * 初始化类的绑定关系
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (init) {
            return;
        }
        init = true;
        log.info("开始初始化自定义绑定关系");
        initMappingBinding(event.getApplicationContext());
    }

    public void initMappingBinding(ApplicationContext applicationContext) {
        String[] beanNamesForType = applicationContext.getBeanNamesForType(MappingBinding.class);
        for (String beanName : beanNamesForType) {
            doInitMappingBinding(beanName, applicationContext);
        }
    }

    public void doInitMappingBinding(String beanName, ApplicationContext applicationContext) {
        MappingBinding mappingBinding = applicationContext.getBean(beanName, MappingBinding.class);

        mappingBinding.binding();
    }
}
